﻿using System.Windows.Forms;
using SdmxMl.GenericMetadata;
using SdmxMl.Common;
using SdmxMl.Helper;

namespace SilcQuest
{
    /// <summary>
    /// Helper class for renumbering question order and setting question year
    /// </summary>
    public class YearAndOrder
    {
        public bool ProcessChange(TreeNode node, MetadataSetType _metadataSet)
        {
            DlgYear aDlg = new DlgYear();
            object tag = node.Tag;
            bool changed = false;

            Artefact artefact = tag as Artefact;
            if (artefact == null)
                artefact = TreeHelper.GetParentArtefact(node);

            if (artefact != null && artefact.IsFinal == false && aDlg.ShowDialog() == DialogResult.OK)
            {
                string year = aDlg.Year;
                if (year.Length == 2 || year.Length == 4)
                {
                    using (new SdmxMl.Helper.CWaitCursor())
                    {
                        if (year.Length == 4)
                            year = year.Substring(2);

                        int number = 1;
                        int.TryParse(aDlg.Number, out number);
                        if (number <= 0)
                            number = 1;

                        foreach (AttributeValueSetType atv in _metadataSet.AttributeValueSetList)
                        {
                            ComponentValueType cvt = atv.TargetValuesTypeList.GetComponentValue("YEAR");
                            if (cvt != null)
                                cvt.Value = year;

                            // Numbering
                            ReportedAttributeType rpa = atv.ReportedAttributeList.GetReportedAttributeOfConcept("WORDER");
                            if (rpa != null)
                                rpa.Value.UpdateDefaultText(number.ToString());
                            ++number;
                        }

                        // Signal to Refresh tree
                        changed = true;
                    }
                }
                else
                    MessageBox.Show("Invalid year");
            }
            return changed;
        }
            
        
    }
}
